from main.script.models import ScriptGroup
from django.db.models import F
from main.script.serializers import ScriptGroupSerializer, ScriptGroupCreateUpdateSerializer
from utils.viewset import CustomModelViewSet
from utils.json_response import SuccessResponse


class ScriptGroupModelViewSet(CustomModelViewSet):
    """
    脚本组管理 的CRUD视图
    """
    queryset = ScriptGroup.objects.all()
    serializer_class = ScriptGroupSerializer
    create_serializer_class = ScriptGroupCreateUpdateSerializer
    update_serializer_class = ScriptGroupCreateUpdateSerializer

    def list(self, request, *args, **kwargs):
        query_set = ScriptGroup.objects.filter(parent__id__isnull=True)
        serializer = ScriptGroupSerializer(query_set, many=True)
        return SuccessResponse(data=serializer.data, message="获取成功")

    def partial_update(self, request, *args, **kwargs):
        src = ScriptGroup.objects.filter(id=kwargs.get('pk')).first()
        if src:
            action = request.data.get('action')
            d_id = request.data.get('d_id')
            dst = ScriptGroup.objects.get(pk=d_id)
            if action == 0:
                src.parent_id = dst.id
                dst = ScriptGroup.objects.filter(parent_id=dst.id).first()
                if not dst:
                    src.save()
                    return SuccessResponse(data='', message="更新成功")
                action = -1
            src.parent_id = dst.parent_id
            if src.sort_id > dst.sort_id:
                if action == -1:
                    dst = ScriptGroup.objects.filter(sort_id__gt=dst.sort_id).last()
                ScriptGroup.objects.filter(sort_id__lt=src.sort_id, sort_id__gte=dst.sort_id).update(
                    sort_id=F('sort_id') + 1)
            else:
                if action == 1:
                    dst = ScriptGroup.objects.filter(sort_id__lt=dst.sort_id).first()
                ScriptGroup.objects.filter(sort_id__lte=dst.sort_id, sort_id__gt=src.sort_id).update(
                    sort_id=F('sort_id') - 1)
            src.sort_id = dst.sort_id
            src.save()
        return SuccessResponse(data='', message="更新成功")
